package com.songshuai.webapi.login.controller;

import com.songshuai.webapi.baseapi.annotations.SysLogger;
import com.songshuai.webapi.login.dto.RespDTO;
import com.songshuai.webapi.login.dto.UserLoginDto;
import com.songshuai.webapi.login.service.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.security.Principal;

@Api("注册登录")
@Slf4j
@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @ApiOperation(value = "注册", notes = "username和password为必选项")
    @PostMapping("/registry")
    //@SysLogger("registry")
    public RespDTO createUser(@RequestBody UserLoginDto user) {
        RespDTO respDTO = check(user);
        if(1==respDTO.code){
            return respDTO;
        }
        return loginService.createUser(user);
    }
    @SysLogger(operation = "permission用户登录",value = "permission_login")
    @ApiOperation(value = "登录", notes = "username和password为必选项")
    @PostMapping("/login")
    public RespDTO login(@RequestBody UserLoginDto user) {
        //参数判读省略
        RespDTO respDTO = check(user);
        if(1==respDTO.code){
            return respDTO;
        }
        return loginService.login(user);
    }


    RespDTO check(UserLoginDto user) {
        if (null == user) {
            return RespDTO.onFail("用户信息为空");
        }
        if(StringUtils.isBlank(user.getUsername())){
            return RespDTO.onFail("用户名为空");
        }
        if(StringUtils.isBlank(user.getPassword())){
            return RespDTO.onFail("密码为空");
        }
        return RespDTO.onSuc(user);
    }



    @ApiOperation(value = "根据用户名获取用户", notes = "根据用户名获取用户")
    @GetMapping("/{username}")
    //@PreAuthorize("hasRole('USER')")
   // @SysLogger("getUserInfo")
   // @PreAuthorize("hasAnyAuthority('ROLE_USER')")
    public RespDTO getUserInfo(@PathVariable("username") String username){
        //参数判读省略
        UserLoginDto user=  loginService.getUserInfo(username);
        return RespDTO.onSuc(user);
    }

    @ApiIgnore
    @RequestMapping(value = "/current", method = RequestMethod.GET)
    public Principal getUser(Principal principal) {

        return principal;
    }
}
